var AV = require('leanengine');
var Promise = require('promise');
const Order = require('./order');
const wxpay = require('./wxpay');
const uuid = require('uuid/v4');
const xlsx = require('xlsx');
const fs = require('fs');
const mineType = require('mime-types');
const https = require('https');
const requestjson = require('request-json');
/**
 * 一个简单的云代码方法
 */
// AV.Cloud.define('hello', function (request) {
//
//     var name = new AV.Query('Item');
//     name.limit(170);// 最多返回 10 条结果
//     name.include("type");// 最多返回 10 条结果
//     name.find().then(function (value) {
//         var data = value
//         for(var i = 0;i<data.length;i++){
//             var id = []
//             var name = []
//             if(data[i].get("type")){
//                 name.push(data[i].get("type").toJSON().name)
//                 id.push(data[i].get("type").toJSON().objectId)
//                 data[i].set('typeId', id);
//                 data[i].set('typeName', name);
//             }
//             // console.log(data[i].get("objectId"))
//             // var todo = AV.Object.createWithoutData('Item', data[i].get("objectId"));
//         }
//
//         return AV.Object.saveAll(data);
//         // return {status: true, data: value};
//     })
// });

/**
 * 小程序创建订单
 */
AV.Cloud.define('order', (request, response) => {
    const user = request.currentUser;
    if (!user) {
        return response.error(new Error('用户未登录'));
    }
    const authData = user.get('authData');
    if (!authData || !authData.lc_weapp) {
        return response.error(new Error('当前用户不是小程序用户'));
    }

    const itemTypeId = request.params.itemTypeId;   //商品类型id
    const itemPriceId = request.params.itemPriceId;  //商品价格id
    const itemTypeQuery = new AV.Query('ItemType');
    itemTypeQuery.get(itemTypeId).then(function (value) {
        var name = value.attributes.name;
        var startColor = value.attributes.startColor;
        var endColor = value.attributes.endColor;
        var buttonColor = value.attributes.buttonColor;
        var picture = value.attributes.picture;
        var titleDescribe = value.attributes.titleDescribe;
        var contentDescribe = value.attributes.contentDescribe;
        var direction = value.attributes.direction;

        const itemPriceQuery = new AV.Query('ItemPrice');
        itemPriceQuery.get(itemPriceId).then(function (value2) {
            var itemPriceDescribe = value2.attributes.describe;
            var minItemPrice = value2.attributes.minPrice;
            var maxItemPrice = value2.attributes.maxPrice;

            const order = new Order();
            order.number = uuid().replace(/-/g, '').substr(0, 5) + new Date().getTime();  //订单编号
            order.status = 'INIT';        //订单状态
            order.giver = request.currentUser;  //赠送者
            order.name = name;   //商品类型——名称
            order.itemPrice = request.params.itemPrice;  //总价
            order.blessings = request.params.blessings;  //祝福语
            order.count = request.params.count; //数量

            order.itemTypeId = itemTypeId;
            order.itemPriceId = itemPriceId;
            order.minItemPrice = minItemPrice;
            order.maxItemPrice = maxItemPrice;

            order.startColor = startColor; //起始渐变色
            order.endColor = endColor;  //结束渐变色
            order.buttonColor = buttonColor; //按钮颜色
            order.picture = picture;  //商品类型图片
            order.titleDescribe = titleDescribe;  //标题描述
            order.contentDescribe = contentDescribe; //内容描述
            order.direction = direction; //渐变色方向
            order.itemPriceDescribe = itemPriceDescribe;  //商品价格描述

            order.ip = request.meta.remoteAddress;  //客户端ip
            if (!(order.ip && /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/.test(order.ip))) {
                order.ip = '127.0.0.1';
            }
            order.tradeType = 'JSAPI';   //交易类型
            // const acl = new AV.ACL();
            // // 只有创建订单的用户可以读，没有人可以写
            // acl.setPublicReadAccess(false);
            // acl.setPublicWriteAccess(false);
            // acl.setReadAccess(user, true);
            // acl.setWriteAccess(user, false);
            // order.setACL(acl);
            order.place().then(() => {
                console.log(`预订单创建成功：订单号 [${order.number}] prepayId [${order.prepayId}]`);
                const payload = {
                    appId: process.env.WEIXIN_APPID,
                    timeStamp: String(Math.floor(Date.now() / 1000)),
                    package: `prepay_id=${order.prepayId}`,
                    signType: 'MD5',
                    nonceStr: String(Math.random()),
                }
                payload.paySign = wxpay.sign(payload);
                payload.objectId = order.id;
                response.success(payload);

            }).catch(error => {
                console.error(error);
                response.error(error);
            });
        })
    });
});

function sendMessage() {
    var query = AV.Query('Global')
    query.get()
}


//抢福袋
//抢福袋并将抢到的用户信息写到OrderDetails(参数是订单id)
AV.Cloud.define('snatchBlessingBag', function (request) {
    //验证登录
    console.log('开始抢福袋的时间：' + new Date().toLocaleString());
    return verifyLogin(request, function (currentUser) {
        //接下来是开始抢福袋，需要的参数是(订单id，当前用户)
        var orderId = request.params.orderId;
        return new Promise(function (resolve, reject) {
            //查询订单数据
            var orderQuery = new AV.Query('Order');
            orderQuery.get(orderId).then(function (value) {

                if (value.attributes.status !== 'SUCCESS') {
                    return resolve({status: 207, message: '当前订单还没有完成支付'})
                } else {
                    //拿到订单编号，福袋数量，赠送人，领取状态，抢福袋的用户，商品类型，商品价格id
                    var count = value.attributes.count;
                    var status = 0;
                    var type = value.attributes.name;
                    var typeId = value.attributes.itemTypeId;
                    var giver = value.attributes.giver;
                    var blessings = value.attributes.blessings;
                    var minItemPrice = value.attributes.minItemPrice;
                    var maxItemPrice = value.attributes.maxItemPrice;

                    var userQuery = new AV.Query('OrderDetails');
                    userQuery.equalTo('orderNumber', value);
                    userQuery.equalTo('user', currentUser);
                    userQuery.find().then(function (result) {
                        if (result.length !== 0) {
                            console.log('已经抢过福袋');
                            var userStatus = result[0].attributes.status;
                            var orderDetailsId = result[0].id;

                            console.log('抢福袋结束的时间：' + new Date().toLocaleString());

                            return resolve({status: 201, data: userStatus, orderDetailsId: orderDetailsId})
                        } else {
                            console.log('没有抢过福袋，现在开始抢福袋。');
                            var orderDetailsQuery = new AV.Query('OrderDetails');
                            orderDetailsQuery.equalTo('orderNumber', value);
                            orderDetailsQuery.find().then(function (value2) {
                                if (value2.length < count) {
                                    console.log('还有剩余的福袋供你抢！');
                                    var OrderDetailsUpdate = AV.Object.extend('OrderDetails');
                                    var orderDetailsUpdate = new OrderDetailsUpdate();

                                    orderDetailsUpdate.set('number', uuid().replace(/-/g, '').substr(0, 5) + new Date().getTime());
                                    orderDetailsUpdate.set('orderNumber', value);
                                    orderDetailsUpdate.set('giver', giver);
                                    orderDetailsUpdate.set('type', type);
                                    orderDetailsUpdate.set('typeId', typeId);
                                    orderDetailsUpdate.set('status', status);
                                    orderDetailsUpdate.set('user', currentUser);
                                    orderDetailsUpdate.set('blessings', blessings);

                                    orderDetailsUpdate.set('featureCode', value.id + currentUser.id);
                                    orderDetailsUpdate.save().then(function (value3) {
                                        //验证用户是否抢到福袋
                                        console.log('验证用户是否抢到福袋');
                                        var checkQuery = new AV.Query('OrderDetails');
                                        checkQuery.equalTo('orderNumber', value);
                                        checkQuery.limit(count);
                                        checkQuery.find().then(function (value4) {

                                            if (value4.length !== 0 && hadGetGiftIndex(value4, value3) !== -1) {


                                                var newOrderDetailsId = value3.id;
                                                var newUpdate = AV.Object.createWithoutData('OrderDetails', newOrderDetailsId);
                                                newUpdate.set('verification', true);
                                                newUpdate.save().then(function (value5) {
                                                    console.log('抢到一个福袋。');

                                                    randomItem(value5.id, status, minItemPrice, maxItemPrice, currentUser).then(function (result) {
                                                        console.log('抢福袋结束的时间：' + new Date().toLocaleString());
                                                        return resolve(result);
                                                    });
                                                });
                                            } else {
                                                console.log('抢福袋结束的时间：' + new Date().toLocaleString());
                                                return resolve({status: 203})
                                            }
                                        })
                                    }, function (reason) {
                                        return resolve({status: 208, message: '当前用户已抢过，不能重复写入'})
                                    })
                                } else {
                                    console.log('抢福袋结束的时间：' + new Date().toLocaleString());
                                    return resolve({status: 204})
                                }
                            })
                        }
                    });
                }
            })
        })
    })
});

function handleArrayData(array) {
    var newArray = [];
    for (var i = 0; i < array.length; i++) {
        newArray.push(array[i].toJSON())
    }
    return newArray;
}

function hadGetGiftIndex(allRobs, robs) {
    var robInfo = robs.toJSON();
    var giftIndex = -1;
    allRobs.forEach(function (item, index) {
        var object = item.toJSON();
        if (object.objectId === robInfo.objectId) {
            giftIndex = index
        }
    });
    return giftIndex;

}


//生成两件随机商品（参数是商品详情的id）
function randomItem(orderDetailsId, userStatus, minPrice, maxPrice, currentUser) {
    console.log('生成随机商品');
    return new Promise(function (resolve, reject) {
        //订单详情里商品类型的查询
        var orderDetailsQuery = new AV.Query('OrderDetails');
        orderDetailsQuery.get(orderDetailsId).then(function (value) {
            var itemTypeId = value.attributes.typeId;
            //获取商品类型的id
            var itemTypeQuery = new AV.Query('ItemType');
            itemTypeQuery.get(itemTypeId).then(function (value2) {
                // 查询所有该类型的商品
                if (value2 === null) {
                    console.log('没有该类型的商品');
                    return resolve({status: 206, message: '没有该类型商品！'})
                } else {
                    console.log('有该类型的商品，开始随机分配两件商品');
                    var itemQuery = new AV.Query('Item');
                    itemQuery.equalTo('typeId', value2.toJSON().objectId);
                    itemQuery.equalTo('onShelf', true)
                    itemQuery.greaterThanOrEqualTo('price', minPrice);
                    itemQuery.lessThanOrEqualTo('price', maxPrice);
                    itemQuery.find().then(function (value3) {
                        var itemLen = value3.length;
                        var count = 2;
                        //生成随机数
                        if (itemLen > 0) {
                            var itemList = randomItemId(value3, count);
                            //将随机生成的商品更新到商品详情
                            var orderDetailsUpdate = AV.Object.createWithoutData('OrderDetails', orderDetailsId);

                            //设定权限
                            var acl = new AV.ACL();
                            acl.setPublicReadAccess(true);
                            acl.setWriteAccess(currentUser, true);
                            acl.setRoleWriteAccess('admin', true);

                            orderDetailsUpdate.setACL(acl);
                            orderDetailsUpdate.set('item', itemList);
                            orderDetailsUpdate.save().then(function (value4) {
                                return resolve({status: 202, data: userStatus, orderDetailsId: orderDetailsId})
                            })
                        } else {
                            console.log('商品不足两件');
                            return resolve({status: 205, message: '商品不足两件'})
                        }
                    })
                }
            })
        })
    })
}

function randomItemId(array, count) {
    var randomItemIdList = [];
    for (var i = 0; i < count; i++) {
        var length = array.length;
        if (length === 0) break;
        var index = Math.floor(Math.random() * length);
        var item = array.splice(index, 1)[0].id;
        randomItemIdList.push(item)
    }
    return randomItemIdList
}

// AV.Cloud.define('randomItem', function (request) {
//     //验证登录
//     return verifyLogin(request, function (surrentUser) {
//         var orderDetailsId = request.params.orderDetailsId;
//         return new Promise(function (resolve, reject) {
//             //订单详情里商品类型的查询
//             var orderDetailsQuery = new AV.Query('OrderDetails');
//             orderDetailsQuery.get(orderDetailsId).then(function (value) {
//                 var itemType = value.attributes.type;
//                 //获取商品类型的id
//                 var itemTypeQuery = new AV.Query('ItemType');
//                 itemTypeQuery.equalTo('name', itemType);
//                 itemTypeQuery.find().then(function (value2) {
//                     // 查询所有该类型的商品
//                     var itemQuery = new AV.Query('Item');
//                     itemQuery.equalTo('type', value2[0]);
//                     itemQuery.find().then(function (value3) {
//                         var itemLen = value3.length;
//                         //生成随机数
//                         if(itemLen >= 2){
//                             var item1 = Math.round(Math.random()*itemLen);
//
//                             do{
//                                 var item2 = Math.round(Math.random()*itemLen);
//                             }while (item2 == item1);
//
//                             var itemId1 = value3[item1].id;
//                             var itemId2 = value3[item2].id;
//                             //将随机生成的商品更新到商品详情
//                             var orderDetailsUpdate = AV.Object.createWithoutData('OrderDetails', orderDetailsId);
//                             orderDetailsUpdate.set('item', [itemId1, itemId2]);
//                             orderDetailsUpdate.save().then(function (value4) {
//                                 return resolve({status: true, data: [itemId1, itemId2]})
//                             })
//                         }else {
//                             console.log('商品不足两件');
//                             return resolve({status: false, data: '商品不足两件'})
//                         }
//                     })
//                 })
//             })
//         })
//
//     })
// });


//用户从随机商品中选择一个商品(参数是商品详情的id和选择的商品id)
AV.Cloud.define('choiceItem', function (request) {
    //验证登录
    return verifyLogin(request, function (currentUser) {
        return new Promise(function (resolve, reject) {
            var orderDetailsId = request.params.orderDetailsId;  //订单详情id
            var selectedItemId = request.params.selectedItemId;  //选择商品的id
            var status = 1;   //已选择状态

            var itemQuery = new AV.Query('Item');
            itemQuery.get(selectedItemId).then(function (item) {
                var goodPoint = AV.Object.createWithoutData('Item', selectedItemId)
                new AV.Query('Image')
                    .equalTo('goods', goodPoint)
                    .ascending('createdAt')
                    .find().then(function (pictureList) {
                    var imageList = []
                    pictureList.forEach(function (picture) {
                        imageList.push(picture.toJSON().file.url)
                    })
                    var itemName = item.attributes.name;
                    var picture = item.attributes.picture;
                    var describe = item.attributes.describe;
                    var price = item.attributes.price;
                    var remind = request.params.remind;

                    //更新订单详情中的商品信息
                    var itemUpdate = AV.Object.createWithoutData('OrderDetails', orderDetailsId);
                    itemUpdate.set('selectedItemId', selectedItemId);
                    itemUpdate.set('status', status);
                    itemUpdate.set('itemName', itemName);
                    itemUpdate.set('picture', picture);
                    itemUpdate.set('describe', describe);
                    itemUpdate.set('price', price);
                    itemUpdate.set('remind', remind);
                    itemUpdate.set('pictureList', imageList)
                    itemUpdate.save().then(function (value2) {
                        return resolve({status: true, orderDetailsId: value2.id})
                    });
                })

            });
        });
    })
});


//验证登录
function verifyLogin(request, cb) {
    if (!request.currentUser) {
        return {status: false, message: '用户未登录'}
    }
    var currentUser = request.currentUser;
    return cb(currentUser);
}

AV.Cloud.define('getFilterOrderData', function (request) {
    console.log('----------filter');
    return new Promise(function (resolve, reject) {
        findOrderByFilter({
            class: request.params.class,
            orderNumber: request.params.id,
            page: request.params.page,
            key: request.params.column,
            value: request.params.str,
            pageCount: request.params.pageCount,
        }, function (data) {
            return resolve(data)
        })
    })
});

function findOrderByFilter(filter, cb) {
    console.log(filter)
    var userQuery = new AV.Query('_User');
    userQuery.equalTo('nickName', filter.value);
    var orderQuery = new AV.Query(filter.class);
    orderQuery.matchesQuery('giver', userQuery);
    orderQuery.include('giver');
    if (filter.orderNumber) {
        orderQuery.equalTo("orderNumber", AV.Object.createWithoutData('Order', filter.orderNumber));
    }
    if (filter.class === "Order") {
        orderQuery.equalTo("status", "SUCCESS");
        orderQuery.greaterThan('itemPrice', 1);
    }
    if (filter.class === 'OrderDetails' && !filter.orderNumber) {
        let innerQuery = new AV.Query('Order');
        innerQuery.equalTo("status", "SUCCESS");
        innerQuery.greaterThan('itemPrice', 1);
        orderQuery.matchesQuery('orderNumber', innerQuery);
    }

    orderQuery.skip((filter.page - 1) * filter.pageCount);
    orderQuery.limit(filter.pageCount);
    orderQuery.descending('createdAt');
    orderQuery.find().then(function (results) {
        if (results.length === 0) {
            return cb({count: 0, list: results})
        } else {
            orderQuery.count().then((count) => {
                return cb({count: count, list: results})
            })
        }
    })

}


AV.Cloud.define('getListFile', function (request) {
    console.log('---------------getListFile')
    return new Promise(function (resolve, reject) {
        request.params.page = request.params.page || 1;
        request.params.pageCount = request.params.pageCount || 1000;
        console.log(request.params)
        console.log('---------start')
        if (request.params.class === "Item") {
            var query = new AV.Query(request.params.class);
            query.addDescending('sort');
            query.addDescending('updatedAt');
            query.include("picture");
            if (request.params.key && request.params.value !== '') {
                if (request.params.key === 'price') {
                    query.equalTo('price', Number(request.params.value));
                } else if (request.params.key === 'objectId') {
                    return query.get(request.params.value).then((todo) => {
                        listFileData([todo], resolve)
                    });

                } else {
                    query.contains(request.params.key, request.params.value);
                }
            }

            query.limit(1000);// 最多返回 10 条结果
            query.find().then((data) => {
                return listFileData(data, resolve);
            })
        }

        if (request.params.class === "Order") {
            let order;
            if (request.params.dateRange && request.params.dateRange.length === 2) {
                let query = new AV.Query('Order');
                query.greaterThanOrEqualTo('createdAt', request.params.dateRange[0]);
                let endDateQuery = new AV.Query('Order');
                endDateQuery.lessThan('createdAt', request.params.dateRange[1]);
                order = AV.Query.and(query, endDateQuery);
            } else {
                order = new AV.Query('Order');
            }

            order.descending('createdAt');
            order.equalTo("status", "SUCCESS");
            order.skip((request.params.page - 1) * request.params.pageCount);
            order.limit(request.params.pageCount);
            order.include('giver');

            if (request.params.key !== '' && request.params.value !== '') {
                if (request.params.key === 'count') {
                    order.equalTo('count', Number(request.params.value));
                } else if (request.params.key === 'itemPrice') {
                    order.equalTo('itemPrice', Number(request.params.value) * 100);
                } else if (request.params.key === 'giver') {
                    return findOrderByFilter({
                        page: request.params.page,
                        value: request.params.value,
                        pageCount: request.params.pageCount,
                        class: 'Order',
                    }, function (data) {
                        listFileData(data.list, resolve)
                    })
                } else {
                    console.log('---------contains')
                    order.contains(request.params.key, request.params.value);
                }
            }
            console.log(order)

            order.find().then((adList) => {
                console.log(adList)
                listFileData(adList, resolve)
            }, (err) => {
                reject(err)
            })
        }

        if (request.params.class === "OrderDetails") {

            let order;
            if (request.params.dateRange.length === 2) {
                let query = new AV.Query('OrderDetails');
                query.greaterThanOrEqualTo('createdAt', request.params.dateRange[0]);
                let endDateQuery = new AV.Query('OrderDetails');
                endDateQuery.lessThan('createdAt', request.params.dateRange[1]);
                order = AV.Query.and(query, endDateQuery);
            } else {
                order = new AV.Query('OrderDetails');
            }
            if (request.params.orderNumber) {
                order.equalTo("orderNumber", AV.Object.createWithoutData('Order', request.params.orderNumber));
            }
            order.skip((request.params.page - 1) * request.params.pageCount);
            order.limit(request.params.pageCount);
            order.descending('createdAt');
            if (request.params.key !== '' && request.params.value !== '') {
                if (request.params.key === 'price') {
                    order.equalTo(request.params.key, Number(request.params.value));
                } else if (request.params.key === 'address') {
                    order.contains(request.params.key, request.params.value);
                } else if (request.params.key === 'status' && getOrderState().indexOf(request.params.value) !== -1) {
                    order.equalTo(request.params.key, getOrderState().indexOf(request.params.value));
                } else if (request.params.key === 'user' || request.params.key === 'giver') {
                    return findOrderByFilter({
                        orderNumber: request.params.id,
                        page: request.params.page,
                        value: request.params.value,
                        pageCount: request.params.pageCount,
                        class: 'Order',
                    }, function (data) {
                        listFileData(data.list, resolve)
                    })
                } else {
                    order.contains(request.params.key, request.params.value);
                }
            }

            order.find().then((adList) => {
                listFileData(adList, resolve)
            }, (err) => {
                reject(err)
            })
        }
    })
});

function getOrderState() {
    return ["已领取", "已选择", "待发货", "已发货"]
}

function listFileData(data, resolve) {
    if (data.length !== 0) {
        var _headers = Object.keys(data[0].attributes);
        var _info = [];

        for (let i = 0; i < data.length; i++) {
            let value = data[i].toJSON();
            for (let key = 0; key < _headers.length; key++) {
                if (value[_headers[key]] && value[_headers[key]].toString() === "[object Object]") {
                    value[_headers[key]] = value[_headers[key]].objectId
                }
            }
            _info.push(value)
        }

        var headers = _headers
            .map((v, i) => Object.assign({}, {v: v, position: String.fromCharCode(65 + i) + 1}))
            .reduce((prev, next) => Object.assign({}, prev, {[next.position]: {v: next.v}}), {});

        var info = _info
            .map((v, i) => _headers.map((k, j) => Object.assign({}, {
                v: v[k],
                position: String.fromCharCode(65 + j) + (i + 2)
            })))
            .reduce((prev, next) => prev.concat(next))
            .reduce((prev, next) => Object.assign({}, prev, {[next.position]: {v: next.v}}), {});

        var output = Object.assign({}, headers, info);
        var outputPos = Object.keys(output);

        var ref = outputPos[0] + ':' + outputPos[outputPos.length - 1];
        var wb = {
            SheetNames: ['mySheet'],
            Sheets: {
                'mySheet': Object.assign({}, output, {'!ref': ref})  //范围 生产数据 !ref
            }
        };
        var fileName = new Date().getTime() + '.xlsx';
        xlsx.writeFile(wb, fileName);


        let fileData = fs.readFileSync('./' + fileName);
        fileData = new Buffer(fileData).toString('base64');

        let base64 = 'data:' + mineType.lookup('./' + fileName) + ';base64,' + fileData;

        var file = new AV.File(fileName, {base64: base64});
        file.save().then((fileInfo) => {
            console.log(fileInfo)
            fs.unlinkSync('./' + fileName);

            return resolve(fileInfo.toJSON())
        });
    } else {
        return resolve('null')
    }
}

AV.Cloud.define('getAccessToken', function (request) {
    var url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx1e52a2cee06be1b2&secret=cb436c553945aa1d51908c67918340f9'
    https.get(url, (res) => {
        const {statusCode} = res;
        const contentType = res.headers['content-type'];
        let error;
        if (statusCode !== 200) {
            error = new Error('请求失败。\n' +
                '状态码: ${statusCode}');
        } else if (!/^application\/json/.test(contentType)) {
            error = new Error('无效的 content-type.\n' +
                '期望 application/json 但获取的是 ${contentType}');
        }
        if (error) {
            console.error(error.message);
            // 消耗响应数据以释放内存
            res.resume();
            return;
        }
        res.setEncoding('utf8');
        let rawData = '';
        res.on('data', (chunk) => {
            rawData += chunk;
        });
        res.on('end', () => {
            try {
                const parsedData = JSON.parse(rawData);
                console.log(parsedData);
                var token = AV.Object.createWithoutData('Global', '5b4b08f8ee920a003c1026b4');
                token.fetch({useMasterKey: true}).then(function () {
                    token.set('value', rawData);
                    token.save();
                }, function (e) {
                    console.error(e.message);
                });
            } catch (e) {
                console.error(e.message);
            }
        });
    }).on('error', (e) => {
        console.error(`错误: ${e.message}`);
    });
})

AV.Cloud.define('getWXAccessToken', function (request) {
    var url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx3cf0f346f6080c78&secret=ebcc52d0c6c5e991e6de4e84cd91db3a'
    https.get(url, (res) => {
        const {statusCode} = res;
        const contentType = res.headers['content-type'];
        let error;
        if (statusCode !== 200) {
            error = new Error('请求失败。\n' +
                '状态码: ${statusCode}');
        } else if (!/^application\/json/.test(contentType)) {
            error = new Error('无效的 content-type.\n' +
                '期望 application/json 但获取的是 ${contentType}');
        }
        if (error) {
            console.error(error.message);
            // 消耗响应数据以释放内存
            res.resume();
            return;
        }
        res.setEncoding('utf8');
        let rawData = '';
        res.on('data', (chunk) => {
            rawData += chunk;
        });
        res.on('end', () => {
            try {
                const parsedData = JSON.parse(rawData);
                var token = AV.Object.createWithoutData('Global', '5b723e089f545400351bbd27');
                token.fetch({useMasterKey: true}).then(function () {
                    console.log(rawData)
                    token.set('value', rawData);
                    token.save();
                }, function (e) {
                    console.error(e.message);
                });
            } catch (e) {
                console.error(e.message);
            }
        });
    }).on('error', (e) => {
        console.error(`错误: ${e.message}`);
    });
})

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function sendTemplateMessage(orderDetailId, isVirtualGift) {
    return new Promise((reslove) => {
        new AV.Query('OrderDetails')
            .include('user')
            .get(orderDetailId).then((orderDetails) => {
            var orderDetailInfo = orderDetails.toJSON();
            if (!orderDetailInfo.remind) {
                return reslove()
            }

            console.log(JSON.stringify(orderDetailInfo))
            let contents = {
                "touser": orderDetailInfo.user.authData.lc_weapp.openid,
                "template_id": "AXuu34zwYs2Q1qsG_jw2OlaWWahuQlvflZYjVZwNH20",
                "form_id": orderDetailInfo.remind,
                "page": "pages/index/index",
                "data": {
                    "keyword1": {
                        "value": orderDetailInfo.itemName
                    },
                    "keyword2": {
                        "value": "礼部 Club Surprise"
                    },
                    "keyword3": {
                        "value": orderDetailInfo.logisticsInfo
                    },
                    "keyword4": {
                        "value": orderDetailInfo.logisticsNum
                    },
                    "keyword5": {
                        "value": new Date(orderDetailInfo.updatedAt).Format("yyyy-MM-dd hh:mm:ss")
                    }
                }
            };

            let virtualGift = {
                "touser": orderDetailInfo.user.authData.lc_weapp.openid,
                "template_id": "AXuu34zwYs2Q1qsG_jw2OjOi9ErGBFatNLOemdehxcY",
                "form_id": orderDetailInfo.remind,
                "page": "pages/index/index",
                "data": {
                    "keyword1": {
                        "value": orderDetailInfo.itemName
                    },
                    "keyword2": {
                        "value": "礼部 Club Surprise"
                    },

                    "keyword3": {
                        "value": new Date(orderDetailInfo.updatedAt).Format("yyyy-MM-dd hh:mm:ss")
                    },
                    "keyword4": {
                        "value": '虚拟商品，请在平台内订单内查收'
                    }
                }
            }

            var messageInfo = isVirtualGift ? virtualGift : contents;

            new AV.Query('Global')
                .get('5b723e089f545400351bbd27', {useMasterKey: true}).then(function (result) {
                var info = result.toJSON().value
                var access_token = JSON.parse(info).access_token
                try {
                    var url = "/cgi-bin/message/wxopen/template/send?access_token=";
                    url += access_token;
                    var client = requestjson.createClient('https://api.weixin.qq.com');
                    client.post(url, messageInfo, function (err, res, body) {
                        console.log(res.statusCode, body);
                        reslove()
                    });
                } catch (e) {
                    console.error(e.message);
                    reslove()
                }

            })


        }, () => {
            reslove()
        })
    })

}


AV.Cloud.define('sendWXMessage', function (request) {
    var giftInfo = request.params;
    console.log(giftInfo)
    return sendTemplateMessage(giftInfo.id, giftInfo.isVirtualGift)
})


AV.Cloud.define('updateOldGiftImgData', function (request) {

    let query = new AV.Query('VirtualGift');
    query.include('goodsQr');
    query.find().then((results) => {
        let allGift = handleArrayData(results);
        for (let i = 0; i < allGift.length; i++) {
            if (allGift[i].goodsQr) {
                let file = AV.File.withURL('virtualGiftImage.png', allGift[i].goodsQr.url);
                file.save().then(function (file) {
                    let virtualGift = new AV.Object('VirtualGiftImage');
                    virtualGift.set('virtualGift', results[i]);
                    virtualGift.set('file', file);
                    virtualGift.save().then((todo) => {
                        let updateQr = AV.Object.createWithoutData('VirtualGift', results[i].id);
                        updateQr.set('goodsQr', null);
                        updateQr.save().then(() => {
                            console.log('---update')
                        })
                    }, function (error) {
                        console.error(error);
                    });
                })
            }
        }
    }, function (error) {
    });

});


function getGoodsByLabel(label, reslove) {
    let startDateQuery = new AV.Query('Item');
    startDateQuery.notContainedIn('label', []);

    let endDateQuery = new AV.Query('Item');
    endDateQuery.containsAll('label', label);

    let query = AV.Query.and(startDateQuery, endDateQuery);
    query.find().then((list) => {
        if (list.length === 0) {
            label.pop();
            return getGoodsByLabel(label, reslove)
        } else {
            return reslove(list)
        }
    });
}

AV.Cloud.define('getGoodsAccordingToLabels', function (request) {
    return new Promise((reslove) => {

        getGoodsByLabel(request.params.label, reslove);
    })
});

